#
# PageRenderer.py
# (c) 2008 Will Baker.
#

from PyQt4.QtCore import Qt, QRect, QPoint, QSize
from PyQt4.QtGui import QPixmap, QPainter

from ComicViewOptions import ComicViewOptions

class PageRenderer:
    """
    Renders a collection of pages. This encapsulates functionality such as page
    rotation, double pages, etc.
    """
    def __init__( self, target, options ):
        self.pages = []
        self.target = target
        self.options = options
        self.width = 0
        self.height = 0
        self.image = None
        
    def push( self, page ):
        self.pages.append( page )
        
        if self.options.rotate == ComicViewOptions.NoRotation:
            self.width += page.image.width()
            self.height = max( self.height, page.image.height() )
        else:
            self.width = max( self.width, page.image.height() )
            self.height += page.image.width()
 
    def prepare( self ):
        if len(self.pages) == 0:
            self.width = 1
            self.height = 1
            self.image = QPixmap( 1, 1 )
            self.image.fill( Qt.black )
        else:
            self.image = QPixmap( self.width, self.height )
            self.image.fill( Qt.white )

            painter = QPainter( self.image )
            x = 0
            for p in self.pages:
                if self.options.rotate == ComicViewOptions.RightRotation:
                    painter.rotate( 90 )
                    painter.translate( 0, -p.image.height() )
                elif self.options.rotate == ComicViewOptions.LeftRotation:
                    painter.rotate( -90 )
                    painter.translate( -p.image.width(), 0 )
                
                if len(self.pages) == 1 or self.options.rotate != ComicViewOptions.LeftRotation:
                    painter.drawPixmap( x, 0, p.image )
                else:
                    painter.drawPixmap( x - self.height/2, 0, p.image )
                    
                x += p.image.width()
                painter.resetMatrix()
                
            painter.end()

    def render( self, context ):
        size = self.options.get_size( self.image.size(), self.target )
        rect = QRect( QPoint(0, 0), size )

        centre = QPoint( self.target.width()/2, self.target.height()/2 )
        offset = QPoint( -size.width()/2, -size.height()/2 )
        scroll = self.options.get_scroll( size, self.target )
        
        context.translate( centre  )
        context.translate( scroll )
        context.translate( offset )
        
        if self.options.refine:
            image = self.image.scaled( rect.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation )
        else:
            image = self.image
        context.drawPixmap( rect, image )

        context.resetMatrix()
        
